package net.butfly.albacore.dao.plugin;

import java.io.Serializable;
import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;

@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public abstract class KeyGeneratorPluginBase<K extends Serializable> implements Interceptor {
	public Object intercept(Invocation invocation) throws Throwable {
		Object[] queryArgs = invocation.getArgs();
		MappedStatement ms = (MappedStatement) queryArgs[0];
		if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
			String keyProp = ms.getKeyProperty();
			Configuration conf = ms.getConfiguration();
			final MetaObject meta = conf.newMetaObject(queryArgs[1]);
			if (null != keyProp && meta.hasSetter(keyProp) && null == meta.getValue(keyProp)) {
				meta.setValue(keyProp, this.generatorKey());
				queryArgs[1] = meta.getOriginalObject();
			}
		}
		return invocation.proceed();
	}

	protected abstract K generatorKey();

	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	public void setProperties(Properties properties) {}
}
